package com.zhentao.config;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Data
@Configuration
@ConfigurationProperties(prefix = "alipay")
public class AliPayConfig {

    private static final Logger logger = LoggerFactory.getLogger(AliPayConfig.class);

    // 基础配置
    private String appId;
    // 沙箱环境网关
    private String gateway = "openapi-sandbox.dl.alipaydev.com"; // 不带 https://
    private String signType = "RSA2";

    // 密钥配置
    private String privateKey;
    private String publicKey;

    // 回调配置
    private String notifyUrl = "http://localhost:8001/alipay/notify";
    private String returnUrl = "http://localhost:8001/alipay/return";

    // 其他配置
    private String charset = "UTF-8";
    private String format = "json";
    private String protocol = "https";

    /**
     * 初始化支付宝SDK配置
     */
    @PostConstruct
    public void init() {
        try {
            Config config = new Config();
            config.protocol = this.protocol;
            config.gatewayHost = this.gateway;  // 使用配置的网关
            config.signType = this.signType;
            config.appId = this.appId;
            config.merchantPrivateKey = this.privateKey
                    .replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "")
                    .trim();
            config.alipayPublicKey = this.publicKey
                    .replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "")
                    .trim();
            config.notifyUrl = this.notifyUrl;

            Factory.setOptions(config);
            logger.info("支付宝SDK初始化完成 | AppID: {} | Gateway: {}", this.appId, this.gateway);
        } catch (Exception e) {
            logger.error("支付宝配置初始化失败", e);
            throw new RuntimeException("支付宝配置初始化失败", e);
        }
    }

    /**
     * 获取完整的网关地址（兼容旧版）
     */
    public String getGatewayUrl() {
        return "https://" + this.gateway + "/gateway.do";
    }
}